package admin

import (
	"github.com/gin-gonic/gin"
	"go_my_framework/app/global/request"
	"go_my_framework/app/service"
	"go_my_framework/util/base"
	"strconv"
)

// 首页
func AdminIndex(c *gin.Context) {
	if c.Request.Method == "POST" {
		// 获取列表
		var f request.AdminForm
		if err := c.ShouldBind(&f); err != nil {
			base.Error(c, err.Error(), nil)
			return
		}
		svc := service.AdminService{}
		list, count, err := svc.GetAdminList(f)
		if err != nil {
			base.Error(c, err.Error(), nil)
			return
		}
		data := make(map[string]interface{})
		data["data"] = list
		data["count"] = count
		base.Success(c, "", data)
	} else {
		// 显示页面
		username := c.Query("username")
		base.Html(c, "/admin/admin/index", gin.H{"username": username})
	}
}

func AdminAdd(c *gin.Context) {
	if c.Request.Method == "POST" {
		var f request.AdminAddForm
		if err := c.ShouldBind(&f); err != nil {
			base.Error(c, err.Error(), nil)
			return
		}
		svc := service.AdminService{}
		err := svc.AddAdmin(f.Username, f.RealName, f.Password, f.RePassword, f.RoleId, f.Mobile)
		if err != nil {
			base.Error(c, err.Error(), nil)
			return
		} else {
			base.Success(c, "提交成功", nil)
			return
		}
	} else {
		var f request.RoleForm
		roleSvc := service.RoleService{}
		roleList, _, _ := roleSvc.GetRoleList(f)
		base.Html(c, "/admin/admin/add", gin.H{"roleList": roleList})
	}
}

func AdminEdit(c *gin.Context) {
	if c.Request.Method == "POST" {
		idStr := c.PostForm("id")
		id, _ := strconv.Atoi(idStr)
		username := c.PostForm("username")
		password := c.DefaultPostForm("password", "")
		rePassword := c.DefaultPostForm("re_password", "")
		roleIdStr := c.PostForm("role_id")
		roleId, _ := strconv.Atoi(roleIdStr)
		realName := c.PostForm("real_name")
		mobile := c.PostForm("mobile")

		svc := service.AdminService{}
		err := svc.EditAdmin(id, username, password, rePassword, roleId, realName, mobile)
		if err != nil {
			base.Error(c, err.Error(), nil)
			return
		} else {
			base.Success(c, "提交成功", nil)
			return
		}
	} else {
		username := c.Query("username")
		svc := service.AdminService{}
		data := svc.GetRow(username)

		var f request.RoleForm
		roleSvc := service.RoleService{}
		roleList, _, _ := roleSvc.GetRoleList(f)
		base.Html(c, "/admin/admin/edit", gin.H{"data": data, "roleList": roleList})
	}
}

func AdminDel(c *gin.Context) {
	idStr := c.PostForm("id")
	id, _ := strconv.Atoi(idStr)
	svc := service.AdminService{}
	err := svc.DelAdmin(id)
	if err != nil {
		base.Error(c, err.Error(), nil)
		return
	} else {
		base.Success(c, "已删除", nil)
		return
	}
}
//
//func editProfile(c *gin.Context) {
//	adminId := redis
//}